package com.linux.huhx.utils;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by huhx on 2017-06-05.
 */
public class BeanUtils {
    private static Logger logger = LoggerFactory.getLogger(BeanUtils.class);

    public static Map<String, Object> bean2Map(Object beanObject) {
        BeanWrapperImpl bean = new BeanWrapperImpl(beanObject);
        PropertyDescriptor desc[] = bean.getPropertyDescriptors();
        Map dataMap = new HashMap(desc.length);
        for (int i = 0; i < desc.length; i++) {
            String name = desc[i].getName();
            // 保证对象的属性是可以读写的,private属性需要需要get和set方法。
            if (bean.isWritableProperty(name) && bean.isReadableProperty(name)) {
                Object object = bean.getPropertyValue(name);
                // 如果对象为空，那么相应的map就没有保存该字段。
                if (object != null) {
                    dataMap.put(name, object);
                }
            }
        }
        return dataMap;
    }

    public static Map<String, String> bean2MapString(Object beanObject) {
        BeanWrapperImpl bean = new BeanWrapperImpl(beanObject);
        PropertyDescriptor desc[] = bean.getPropertyDescriptors();
        Map dataMap = new HashMap(desc.length);
        for (int i = 0; i < desc.length; i++) {
            String name = desc[i].getName();
            // 保证对象的属性是可以读写的,private属性需要需要get和set方法。
            if (bean.isWritableProperty(name) && bean.isReadableProperty(name)) {
                String object = (String) bean.getPropertyValue(name);
                // 如果对象为空，那么相应的map就没有保存该字段。
                if (object != null) {
                    dataMap.put(name, object);
                }
            }
        }
        return dataMap;
    }

    // 没有考虑枚举的情况
    private <T> T map2Bean(Map<String, Object> map, Class<T> clazz) {
        BeanWrapper bw = new BeanWrapperImpl(clazz);
        PropertyDescriptor props[] = bw.getPropertyDescriptors();
        PropertyDescriptor apropertydescriptor[];
        int j = (apropertydescriptor = props).length;
        for (int i = 0; i < j; i++) {
            PropertyDescriptor pd = apropertydescriptor[i];
            String name = pd.getName();
            if (bw.isWritableProperty(name) && bw.isReadableProperty(name)) {
                Object value = map.get(name);
                if (value != null) {
                    bw.setPropertyValue(name, value);
                }
            }
        }
        return (T) bw.getWrappedInstance();
    }
}
